<template>
  <div class="allView">
    <div class="allView_tagChange">
      <n-space class="allView_tagChange_list" v-for="(list, index) in chooseTagList">
        <n-radio-group :value="chooseList[index].value">
          <n-radio-button
            class="allView_tagChange_list_item"
            v-for="item in list"
            :label="item.label"
            :value="item.value"
            @click="changeChooseList(item, index)"
          />
        </n-radio-group>
      </n-space>
      <div class="button-group">
        <n-button type="primary" @click="handleSearch">筛选</n-button>
        <n-button secondary strong @click="resetChooseList">重置</n-button>
        <div class="button-group_search oneLine" v-if="search">
          <span class="button-group_search_text">关键词：</span>
          <n-performant-ellipsis style="max-width: 10em">
            {{ search }}
          </n-performant-ellipsis>
        </div>
      </div>
      <!-- {{ chooseList }}/{{ search }} -->
    </div>
    <n-spin :show="loading">
      <n-empty v-if="loading || paginatedList.length === 0" description="暂无数据" />
      <div class="allView_list" v-else>
        <OneVideo  
          :key="currentPage" 
          :styleMain="{
            'grid-template-columns': 'repeat(auto-fill, minmax(15%, 1fr))',
            'gap': '1rem'
          }" 
          :data="paginatedList" 
          :clickListOne="clickListOne"
        />
      </div>
      <n-divider />
      <div class="allView_pagination">
        <n-pagination v-model:page="indexPage" :page-count="maxPage" show-quick-jumper>
          <template #goto>
            跳转
          </template>
        </n-pagination>
      </div>
    </n-spin>
  </div>
</template>
<script setup>
import { NSpace, NRadioButton, NRadioGroup,NSpin,NPagination,NDivider,NButton,NPerformantEllipsis ,NEmpty} from "naive-ui";
import { computed, onMounted, ref, watch } from "vue";
import OneVideo from "@/components/OneVideo.vue";
import {useRouter,useRoute} from 'vue-router';
import { request } from "@/utils/request";
onMounted(async()=>{
  loading.value = true;
  await Promise.all([
    request({
      url:'/get_video_list/',
      method: "GET",
    }),
    request({
      url:'/get_video_tag_options/',
      method: "GET",
    })
  ]).then(res=>{
     console.log("AllView初始化 数据/标签",res);
     if(res[0].code === 200){
      getListData.value = res[0].data;
      showList.value = getListData.value;
      loading.value = false;   
     }
     if(res[1].code === 200){
      chooseItemTag.value = Object.entries(res[1].data.showTag).map(([key, value]) => ({
        value: key,
        label: value
      }));
      chooseTagList.value=[];
      for (let key in res[1].data.showTag){
        chooseTagList.value.push(Object.entries(res[1].data[key]).map(([key, value]) => ({
          value: key,
          label: value
        })));
      }
      chooseList.value=[];
      for(let i=0;i<chooseTagList.value.length;i++){
        chooseList.value.push(chooseTagList.value[i][0]);
      }
     }
  }).finally(()=>{
    loading.value = false;
    handleSearch();
  })
})
const router = useRouter();
const route = useRoute();
const getListData = ref([]);
const showList = ref([]);
const loading = ref(true);
const chooseItemTag=ref([]);//选中的对应数据中的标签
const chooseTagList = ref([]);//标签列表
const chooseList = ref([]);// 选中的标签
const resetChooseList = ()=>{//重置标签
  chooseList.value=[];
  for(let i=0;i<chooseTagList.value.length;i++){
    chooseList.value.push(chooseTagList.value[i][0]);
  }
  indexPage.value = 1;
  router.replace({query:{}});
  handleSearch();
}
const changeChooseList = (item, index) => {
  chooseList.value[index] = item;
};
const search = computed(()=>route.query.search);
const handleSearch = () => {
  // 获取已选择的非默认标签
  const activeFilters = chooseList.value
    .map((tag, index) => tag !== chooseTagList.value[index][0] ? tag.value : null)
    .filter(tag => tag !== null);
  
  console.log("activeFilters", activeFilters);
  
  // 如果没有过滤条件且没有搜索关键词，显示所有数据
  if (activeFilters.length === 0 && !search.value) {
    showList.value = getListData.value;
    return;
  }

  // 过滤数据
    showList.value = getListData.value.filter(item => {
      let showTag=[]
      chooseItemTag.value.forEach(key=>{
        showTag.push(item[key.label]);
      })
    // 标签过滤
    const matchesTags = activeFilters.length === 0 || 
      activeFilters.every(filter => 
          showTag  && showTag.includes(filter)
      );
    // 关键词过滤
    const matchesSearch = !search.value || 
      (item.title && item.title.includes(search.value));

    return matchesTags && matchesSearch;
  });
  
  console.log("showList", showList.value);
}

const indexPage = ref(1);
const PAGE_SIZE = 36; // 定义每页显示数量
const paginatedList = computed(() => {
  if (!showList.value || !getListData.value) return [];  // 添加空值检查
  const start = Math.max((indexPage.value - 1) * PAGE_SIZE, 0);
  const end = Math.min(start + PAGE_SIZE, showList.value.length);  // 改用 showList 而不是 getListData
  return showList.value.slice(start, end);
});
const maxPage = computed(() => 
  Math.ceil(showList.value.length / PAGE_SIZE)
);

watch(()=>search.value,async ()=>{ 
  handleSearch();
})
const clickListOne = (e)=>{
  router.push(`/Detail/${e.id}`)
}
</script>
<style lang="scss" scoped>
@import '@/styles/base.scss';
.allView {
 padding: 1rem  0.5rem;
  &_tagChange {
    margin: 10px;
    &_list {
      margin: 5px;
    }
    .button-group {
      margin: 5px;
      display: flex;
      gap: 1rem;
      align-items: center;
      &_search {
        color: #999;
        &_text {
          font-size: 0.8rem;
          font-weight: bold;
        }
      }
    }
  }
  &_list {
    padding: 1rem;
  }
  &_pagination {
    margin: 1rem;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
